<template>
	<base-input v-model="mobile" labelT="account.mobile" type="code" :error="mobileError">
		<template #prefix>
			<base-dropdown v-model="mobileCode" :options="codes" :width="200">
				<div class="flex items-center cursor-pointer">
					{{ mobileCode }}
					<base-icon name="down" class="mx-1"></base-icon>
					<div class="mr-2 w-[1px] h-[10px] bg-t-3"></div>
				</div>
			</base-dropdown>
		</template>
	</base-input>
</template>

<script lang="ts" setup>
import { BaseIcon, BaseInput, BaseDropdown } from '@/components/base'
import { ref, watch, Ref, computed } from 'vue'
import { getCountries } from '@/api/assistants'
import { useAppStore, useProfileStore } from '@/store'
import { isMobile, t } from '@/utils'

const props = defineProps({
	modelValue: {
		type: String,
		required: true
	}
})

const emits = defineEmits(['update:modelValue'])

const appStore = useAppStore()

const mobile = ref('')

const mobileCode = ref('')

const codes: Ref<any[]> = ref([])

const mobileError = computed(() =>
	mobile.value && !isMobile(mobile.value) ? t('error.mobile') : ''
)

watch(
	() => [mobile.value, mobileCode.value],
	() => {
		emits('update:modelValue', mobileCode.value + ' ' + mobile.value)
	}
)

const init = async () => {
	const profileStore = useProfileStore()
	const vals = props.modelValue.split(' ')
	if (vals.length > 1) {
		mobileCode.value = vals[0]
		mobile.value = vals[1]
	}
	try {
		const { data } = await getCountries({
			locale: appStore.lang
		})
		data.forEach((item: any) => {
			const { name, callingCode, location } = item
			if (callingCode) {
				callingCode.forEach((code: string) =>
					codes.value.push({ text: name, icon: `region/${location}.svg`, id: code, location })
				)
			}
		})
		if (codes.value.length) {
			const callingCode = codes.value.find(
				(item) => item.location === profileStore.userInfo?.location
			)
			mobileCode.value = callingCode?.id || codes.value[0].id
		}
	} catch {}
}

init()
</script>
